import { defineStore } from 'pinia';
import { v4 as uuidv4 } from 'uuid';

export const useFacilityStore = defineStore('facility', {
  state: () => ({
    facilities: [],
    currentViewMode: '2D',
  }),
  
  getters: {
    getFacilitiesByType: (state) => (type) => {
      return state.facilities.filter(facility => facility.type === type);
    },
    
    getFacilityById: (state) => (id) => {
      return state.facilities.find(facility => facility.id === id);
    },
    
    getAllFacilities: (state) => {
      return state.facilities;
    }
  },
  
  actions: {
    addFacility(facilityData) {
      const newFacility = {
        id: uuidv4(),
        createdAt: new Date().toISOString(),
        ...facilityData
      };
      
      this.facilities.push(newFacility);
      this.saveFacilitiesToStorage();
      return newFacility;
    },
    
    updateFacility(id, updateData) {
      const index = this.facilities.findIndex(facility => facility.id === id);
      if (index !== -1) {
        this.facilities[index] = {
          ...this.facilities[index],
          ...updateData,
          updatedAt: new Date().toISOString()
        };
        this.saveFacilitiesToStorage();
        return this.facilities[index];
      }
      return null;
    },
    
    deleteFacility(id) {
      const index = this.facilities.findIndex(facility => facility.id === id);
      if (index !== -1) {
        this.facilities.splice(index, 1);
        this.saveFacilitiesToStorage();
        return true;
      }
      return false;
    },
    
    toggleViewMode() {
      this.currentViewMode = this.currentViewMode === '2D' ? '3D' : '2D';
      this.saveViewModeToStorage();
    },
    
    setViewMode(mode) {
      if (mode === '2D' || mode === '3D') {
        this.currentViewMode = mode;
        this.saveViewModeToStorage();
      }
    },
    
    loadFacilitiesFromStorage() {
      try {
        const storedFacilities = uni.getStorageSync('facilities');
        if (storedFacilities) {
          this.facilities = JSON.parse(storedFacilities);
        }
        
        // 同时加载视图模式
        this.loadViewModeFromStorage();
      } catch (e) {
        console.error('加载设施数据失败:', e);
      }
    },
    
    loadViewModeFromStorage() {
      try {
        const storedViewMode = uni.getStorageSync('viewMode');
        if (storedViewMode && (storedViewMode === '2D' || storedViewMode === '3D')) {
          this.currentViewMode = storedViewMode;
        }
      } catch (e) {
        console.error('加载视图模式失败:', e);
      }
    },
    
    saveFacilitiesToStorage() {
      try {
        uni.setStorageSync('facilities', JSON.stringify(this.facilities));
      } catch (e) {
        console.error('保存设施数据失败:', e);
      }
    },
    
    saveViewModeToStorage() {
      try {
        uni.setStorageSync('viewMode', this.currentViewMode);
      } catch (e) {
        console.error('保存视图模式失败:', e);
      }
    }
  }
}); 